import '@/js/layui_exts/admin.js'

export function init() {
    layui.use(() => {
        const $ = layui.jquery, treeTable = layui.treeTable, admin = layui.admin, form = layui.form
        const renderRowBg = () => $('#auth-treetable').next('.layui-table-tree').children('.layui-table-box').children('.layui-table-body').children('table').children('tbody').children('tr').each((i, tr) => {
            admin.perm()
            switch ($(tr).children('td[data-field="type"]').attr('data-content')) {
                case 'api':
                    $(tr).css('backgroundColor', '#fafafa')
                    break;
            }
        })

        const emptyNonContainer = op =>
                $('#' + (op === 'add' ? 'modify' : 'add') + '-auth-type-container').empty(),
            renderMenuType = (op, data) => {
                emptyNonContainer(op)
                $('#' + op + '-auth-type-container').html('' +
                    '<div class="layui-form-item">\n' +
                    '    <label class="layui-form-label required">名称：</label>\n' +
                    '    <div class="layui-input-block">\n' +
                    '        <input type="text" name="title" value="' + (data && data.title ? data.title : '') + '" lay-verify="required" placeholder="请填写权限名称……"\n' +
                    '               autocomplete="off"\n' +
                    '               class="layui-input" lay-affix="clear"/>\n' +
                    '    </div>\n' +
                    '</div>\n' +
                    '\n' +
                    '<div class="layui-form-item">\n' +
                    '    <label class="layui-form-label">图标：</label>\n' +
                    '    <div class="layui-input-block">\n' +
                    '        <input type="text" name="sub" value="' + (data && data.sub ? data.sub : '') + '" placeholder="一级菜单请填写图标class……" autocomplete="off"\n' +
                    '               class="layui-input" lay-affix="clear"/>\n' +
                    '    </div>\n' +
                    '</div>\n' +
                    '\n' +
                    '<div class="layui-form-item">\n' +
                    '    <label class="layui-form-label">路由：</label>\n' +
                    '    <div class="layui-input-block">\n' +
                    '        <input type="text" name="uri" value="' + (data && data.uri ? data.uri : '') + '" placeholder="末级菜单请填写路由地址……" autocomplete="off"\n' +
                    '               class="layui-input" lay-affix="clear"/>\n' +
                    '    </div>\n' +
                    '</div>')
            },
            titleGanged = mapping => {
                form.on('select(title-filter)', d => {
                    $('select[name=uri]')[0].value = mapping[d.value]
                    form.render('select')
                })

                form.on('select(uri-filter)', d => {
                    $('select[name=title]')[0].value = mapping[d.value]
                    form.render('select')
                })
            },
            renderBtnApiType = (op, type, auth) => {
                emptyNonContainer(op)
                admin.get('sys/auth_anno/group_list', undefined, ({data}) => {
                    $('#' + op + '-auth-type-container').html('' +
                        '<div class="layui-form-item">\n' +
                        '    <label class="layui-form-label required">名称：</label>\n' +
                        '    <div class="layui-input-block">\n' +
                        '        <select name="title" lay-search lay-filter="title-filter" lay-verify="required">\n' +
                        '            <option value="">请选择名称</option>\n' +
                        data.reduce((p, c) => {
                            p += '<optgroup label="' + c.label + '">' +
                                c.options.reduce((pp, cc) => {
                                    pp += '<option value="' + cc.desz + '" ' + (auth && auth.title === cc.desz ? 'selected' : '') + '>' + cc.desz + '</option>\n'
                                    return pp
                                }, '') +
                                '</optgroup>'
                            return p
                        }, '') +
                        '        </select>\n' +
                        '    </div>\n' +
                        '</div>\n' +
                        '<div class="layui-form-item">\n' +
                        '    <label class="layui-form-label required">编码：</label>\n' +
                        '    <div class="layui-input-block">\n' +
                        '        <select name="uri" lay-search lay-filter="uri-filter" lay-verify="required">\n' +
                        '            <option value="">请选择编码</option>\n' +
                        data.reduce((p, c) => {
                            p += '<optgroup label="' + c.label + '">' +
                                c.options.reduce((pp, cc) => {
                                    pp += '<option value="' + cc.code + '" ' + (auth && auth.uri === cc.code ? 'selected' : '') + '>' + cc.code + '</option>\n'
                                    return pp
                                }, '') +
                                '</optgroup>'
                            return p
                        }, '') +
                        '        </select>\n' +
                        '    </div>\n' +
                        '</div>')
                    form.render('select')
                    let mapping = {}
                    data.forEach(d => d.options.forEach(o => (mapping[o.desz] = o.code, mapping[o.code] = o.desz)))

                    titleGanged(mapping)
                })
            },
            adAuth = data => {
                layer.open({
                    type: 1,
                    title: '<i class="layui-icon-add-circle layui-icon"></i>&nbsp;添加权限【' + data.title + '】',
                    offset: 'r',
                    anim: 'slideLeft',
                    shade: 0.3,
                    area: ['500px', '100%'],
                    shadeClose: true,
                    scrollbar: false,
                    id: 'add-auth-id',
                    content: $('#add-auth-content')
                })
                $('#add-auth-type-container').empty()
                form.val('add-auth-form-filter', {'id': data.id, 'sort': '', 'desz': '', 'rid': data.LAY_DATA_INDEX})
                admin.jsonRadio('level', {'child': '下级权限', 'brother': '同级权限'}, undefined, true)
                admin.enumRadio('type', 'authType', undefined, true)

                form.on('radio(type-filter)', ({value}) => {
                    switch (value) {
                        case 'menu':
                            renderMenuType('add')
                            break;
                        case 'api':
                            renderBtnApiType('add', value)
                            break;
                    }
                })
            }
        const mdAuth = data => admin.post('sys/auth/get', {id: data.id}, ({data: d}) => {
            layer.open({
                type: 1,
                title: '<i class="layui-icon-edit layui-icon"></i>&nbsp;编辑权限【' + data.title + '】',
                offset: 'r',
                anim: 'slideLeft',
                shade: 0.3,
                area: ['500px', '100%'],
                shadeClose: true,
                scrollbar: false,
                id: 'modify-auth-id',
                content: $('#modify-auth-content')
            })
            $('#modify-auth-type-container').empty()
            $('input[name=rid]').val(data.LAY_DATA_INDEX)
            form.val('modify-auth-form-filter', d)

            switch (d.type) {
                case 'menu':
                    renderMenuType('modify', d)
                    break;
                case 'api':
                    renderBtnApiType('modify', d.type, d)
                    break;
            }
        })
        const rmAuth = data => admin.confirm('确定删除【' + data.title + '】', () => {
            admin.postM('sys/auth/remove', {id: data.id}, () => {
                treeTable.removeNode('auth-treetable', data.LAY_DATA_INDEX)
                renderRowBg()
            })
        }, '删除提示')
        admin.enumObj('authType').then(authTypeObj => {

            treeTable.render({
                elem: '#auth-treetable',
                url: '/api/sys/auth/treetable',
                headers: {
                    'Authorization': admin.getToken()
                },
                tree: {
                    customName: {
                        name: 'title'
                    },
                    view: {
                        showIcon: false
                    }
                },
                toolbar: '#auth-treetable-toolbar',
                height: 'full-' + (51 + parseInt($('.layui-layout-admin .layui-body').css('padding-bottom'), 10)),
                defaultToolbar: [
                    'filter',
                    'exports',
                    'print', {
                        title: '更新api方法',
                        name: 'tips',
                        layEvent: 'api-update-tips',
                        icon: 'sys-icon-api sys-icon',
                        onClick: () => admin.confirm('确定刷新权限列表吗？', () => admin.postM('sys/auth_anno/scan'), '操作确认')
                    }
                ],
                parseData: ({code, msg, data}) => {
                    let d = JSON.parse(admin.decrypt(data))
                    return {
                        "code": code === 200 ? 0 : code,
                        "msg": msg,
                        "count": d.length,
                        "data": d
                    }
                },
                cols: [[{
                    type: 'numbers',
                    title: '序号'
                }, {
                    field: 'title',
                    title: '名称'
                }, {
                    field: 'type',
                    title: '类型',
                    align: 'center',
                    width: 100,
                    templet: d => authTypeObj[d.type]
                }, {
                    field: 'uri',
                    title: '方法/路由'
                }, {
                    field: 'sub',
                    align: 'center',
                    title: '图标',
                    templet: d => d.type === 'menu' && d.sub && d.sub.length > 0 ? '<i class="' + d.sub + '"></i>' : d.sub ?? ''
                }, {
                    field: "desz",
                    title: "说明"
                }, {
                    title: '操作',
                    align: 'center',
                    toolbar: '#auth-treetable-tools'
                }]],
                page: false,
                done: () => renderRowBg()
            })
            treeTable.on("toolbar(auth-treetable)", ({event}) => {
                switch (event) {
                    case 'expend':
                        treeTable.expandAll('auth-treetable', true)
                        renderRowBg()
                        break;

                    case 'fold':
                        treeTable.expandAll('auth-treetable', false)
                        break;
                }
            })
            treeTable.on("tool(auth-treetable)", ({event, data}) => {
                switch (event) {
                    case 'ad':
                        adAuth(data)
                        break;

                    case 'md':
                        mdAuth(data)
                        break;

                    case 'rm':
                        rmAuth(data)
                        break;
                }
            })
        })

        form.on('submit(submit-add-auth-form)', ({field}) => {
            admin.postM('sys/auth/add', field, ({data}) => {
                layer.closeAll('page')
                let rid = $('input[name=rid]').val()
                treeTable.addNodes('auth-treetable', {
                    parentIndex: field.level === 'child' ? rid : (rid.indexOf('-') > -1 ? rid.substring(0, rid.lastIndexOf('-')) : ''),
                    index: data.id,
                    data: data
                })
                renderRowBg()
            })
            return false
        })
        form.on('submit(submit-modify-auth-form)', ({field}) => {
            admin.postM('sys/auth/modify', field, ({data}) => {
                layer.closeAll('page')
                treeTable.updateNode('auth-treetable', field.rid, data)
                renderRowBg()
            })
            return false
        })
    })

    return {};
}
